package com.dsteiner.gwt.cafeteriasophia.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.apache.commons.httpclient.util.DateUtil;

import com.dsteiner.gwt.cafeteriasophia.client.domain.ShiftChange;
import com.dsteiner.gwt.cafeteriasophia.client.model.ShiftChangeSelectionModel;
import com.dsteiner.gwt.cafeteriasophia.client.model.StatisticModel;
import com.dsteiner.widgets.client.DateUtilImpl;
import com.dsteiner.widgets.client.Widgets.IHTML;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.SelectionInput;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

public class ShiftChangeSelectionController {

	private ShiftChangeSelectionModel shiftChangeSelectionModel;
	private StatisticModel statisticModel;
	private IHTML infoHtml;
	private SelectionInput checkBox;

	public void registerInfoHtml(IHTML infoHtml) {
		this.infoHtml = infoHtml;
	}

	public void registerShiftChangeSelectionModel(ShiftChangeSelectionModel shiftChangeSelectionModel) {
		this.shiftChangeSelectionModel = shiftChangeSelectionModel;
		shiftChangeSelectionModel.addPropertyChangeListener("shiftChange", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateShiftChangeInfo();
			}
		});
		shiftChangeSelectionModel.addPropertyChangeListener("selected", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateShiftChangeSelection();
			}
		});
	}

	private void updateShiftChangeSelection() {
		boolean selected = shiftChangeSelectionModel.isSelected();
		checkBox.setChecked(selected);
		ShiftChange shiftChange = shiftChangeSelectionModel.getShiftChange();
		if(selected)
			statisticModel.addShiftChangeSelection(shiftChange);
		else
			statisticModel.removeShiftChangeSelection(shiftChange);
			
	}

	public void registerShiftChangeSelectionWidget(ILazyWidget shiftChangeSelectionWidget) {
		shiftChangeSelectionWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
				updateShiftChangeInfo();
			}
		});
	}

	public void registerStatisticModel(StatisticModel statisticModel) {
		this.statisticModel = statisticModel;
	}

	private void updateShiftChangeInfo() {
		ShiftChange shiftChange = shiftChangeSelectionModel.getShiftChange();
		if(shiftChange == null)
			return;
		infoHtml.setHTML(DateUtilImpl.getInstance().formatDateSpanish(shiftChange.getDate())+":"+shiftChange.getEmployee());
	}

	public void registerCheckBox(final SelectionInput checkBox) {
		this.checkBox = checkBox;
		checkBox.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				shiftChangeSelectionModel.setSelected(checkBox.isChecked());
			}
		});
	}
}